package com.jindianjichi.infra.config;

import com.jindianjichi.subject.common.context.LoginContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;

import static jdk.nashorn.internal.objects.NativeString.replace;
import static org.apache.ibatis.javassist.compiler.MemberResolver.getSuperclass;

/**
 * 公共字段填充
 */
@Component
@Slf4j
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class MybatisInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object patameter = invocation.getArgs()[1];
        if(patameter==null){
            return invocation.proceed();
        }
        //获取当前登录用户id
        String loginId = LoginContextHolder.getLoginId();
        if(StringUtils.isBlank(loginId)){
            return invocation.proceed();
        }
        if(SqlCommandType.INSERT.equals(sqlCommandType)||SqlCommandType.UPDATE.equals(sqlCommandType)){

            replaceEntityProperty(patameter,loginId,sqlCommandType) ;
        }
        return invocation.proceed();

    }

    private void replaceEntityProperty(Object patameter, String loginId, SqlCommandType sqlCommandType) {
        if (patameter instanceof Map) {
            replaceMap((Map) patameter, loginId, sqlCommandType);
        }else{
            replace(patameter,loginId,sqlCommandType) ;
        }

    }
    private void replaceMap(Map patameter, String loginId, SqlCommandType sqlCommandType) {
        for(Object val:patameter.values()) {
            replace(val,loginId,sqlCommandType);
        }
    }
    private void replace(Object patameter, String loginId, SqlCommandType sqlCommandType) {
        if (sqlCommandType.equals(SqlCommandType.INSERT)){
            //新增的处理
            dealInsert(patameter,loginId);

        }else if (sqlCommandType.equals(SqlCommandType.UPDATE)){
            //更新处理
            dealUpdate(patameter,loginId);
        }
    }

    private void dealUpdate(Object patameter, String loginId) {
        Field[] fields = getAllFields(patameter);
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                Object o = field.get(patameter);
                if (Objects.nonNull(o)) {
                    field.setAccessible(false);
                    continue;
                }
                if ("updateBy".equals(field.getName())) {
                    field.set(patameter, loginId);
                    field.setAccessible(false);
                } else if ("updateTime".equals(field.getName())) {
                    field.set(patameter, new Date());
                    field.setAccessible(false);
                }
                else {
                    field.setAccessible(false);
                }

            } catch (IllegalAccessException e) {
                log.error("dealUpdate.error:{}", e.getMessage());
            }

        }
    }

    private void dealInsert(Object patameter, String loginId) {
        Field[] fields = getAllFields(patameter);
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                Object o = field.get(patameter);
                if (Objects.nonNull(o)) {
                    field.setAccessible(false);
                    continue;
                }
                if ("updateBy".equals(field.getName())) {
                    field.set(patameter, loginId);
                    field.setAccessible(false);
                } else if ("updateTime".equals(field.getName())) {
                    field.set(patameter, new Date());
                    field.setAccessible(false);
                }else if ("isDeleted".equals(field.getName())) {
                    field.set(patameter, 0);
                    field.setAccessible(false);
                } else if ("createdBy".equals(field.getName())) {
                    field.set(patameter, loginId);
                    field.setAccessible(false);
                } else if ("createdTime".equals(field.getName())) {
                    field.set(patameter, new Date());
                    field.setAccessible(false);
                }
                else {
                    field.setAccessible(false);
                }

            } catch (IllegalAccessException e) {
                log.error("dealInsert.error:{}", e.getMessage());
            }

        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    private Field[] getAllFields(Object object){
        Class<?> clazz = object.getClass();
        List<Field> fieldList = new ArrayList<>();
        while (clazz!=null){
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
           clazz= clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        return fieldList.toArray(fields);

    };
}
